import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class JDBCDemo {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        //接下来  通过JDBC 进行一个插入操作
        //1.创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java113?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("665181");

        //2.和数据库进行连接
        Connection connection =  dataSource.getConnection();

        System.out.println("请输入学号: ");
        int id  = scanner.nextInt();
        System.out.println("请输入姓名: ");
        String name = scanner.next();

        //3.能够 构造一个操作数据库的sql语句

        String sql = "insert into test values(?,?)";

        //String sql = "insert into test values(1,'张三')";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,id);
        preparedStatement.setString(2,name);

        //4.执行sql,把刚才解析好的语句发给数据库服务器了
        //  返回值 是一个int类型的 ,表示这个操作影响了几行
        int n = preparedStatement.executeUpdate();
        System.out.println("n = " + n);

        //5.收尾  释放前面创建的各种资源
        preparedStatement.close();
        connection.close();
    }
}
